//
//  ComposeViewController.swift
//  01MicroBlog
//
//  Created by Apple on 15/8/9.
//  Copyright © 2015年 heima. All rights reserved.
//

import UIKit

class ComposeViewController: UIViewController {

    // MARK: - 1.传闭包给表情键盘
    private lazy var emoticonVc:EmoticonViewController = EmoticonViewController {
        [weak self] (emoticon) -> () in
        
        self?.textView.insertEmoticon(emoticon)
        
    }
    
    // MARK: - 视图的生命周期函数
    override func loadView() {
        view = UIView()
        
        // 视图控制器，一定要设置背景颜色
        // 如果发现动画切换视图控制器变慢，或者闪烁，重点检查是否设置了背景颜色！
        view.backgroundColor = UIColor.whiteColor()
        
        // 1. 按照先后顺序依次添加视图
//        view.addSubview(textView)
//        view.addSubview(photoSelectorVC.view)
//        view.addSubview(toolbar)
        
        // 2. 添加子控制器，开发中如果遇到添加子控制器，一定要使用 addChildViewController
        // 否则有可能造成响应者链条断裂
        addChildViewController(photoSelectorVC)

        
        prepareNavgationBar()
        prepareToolbar()
        prepareTextView()
        preparePhotoView()
        view.bringSubviewToFront(toolbar)
    }
    
    /// 准备照片选择视图
    private func preparePhotoView() {
        
        // 1. 自动布局
        var s = UIScreen.mainScreen().bounds.size
        // swift 允许直接修改结构体中的属性
        s.height = 0.6 * s.height
        photoSelectorVC.view.backgroundColor = UIColor.redColor()
        
        photoSelectorVC.view.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: s)
    }
    
    override func viewDidAppear(animated: Bool) {
        addKeyboardNotification()
        textView.becomeFirstResponder()
    }
    
    var toolBarBottomCons:NSLayoutConstraint?
    
    // MARK: - 发布微博
    func sendStatus() {
        
        print("发送微博")
        // 获取发布微博的图片 如果用户没有选择，image == nil
        let image = photoSelectorVC.photos.last
        
        NetworkTools.sharedNetworkTools.sendStatus(textView.text, image: image) { (result, error) -> () in
            if error != nil {
                print("发送失败")
            } else {
                print("发送成功")
                self.close()
            }
        }
    }
    
    func close() {
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    // MARK: - 2.选择表情控制器
    func inputEmoticon() {
        
//        removedKeyboardNotification()
        
        textView.resignFirstResponder()
        textView.inputView = (textView.inputView == nil) ? emoticonVc.view : nil
        
//        addKeyboardNotification()
        textView.becomeFirstResponder()
    }
    
    /// 照片选择控制器
    private lazy var photoSelectorVC: PhotoSelectorViewController = PhotoSelectorViewController()
    
    func pickPicture() {
        print("选择照片")
//        presentViewController(PhotoSelectorViewController(), animated: true, completion: nil)
    }
    
    private func addKeyboardNotification() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "receiveKeyboardNotification:", name: UIKeyboardWillShowNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "receiveKeyboardNotification:", name: UIKeyboardWillHideNotification, object: nil)
    }
    
    func receiveKeyboardNotification(n:NSNotification) {
        print(n)
        
        let curve = n.userInfo![UIKeyboardAnimationCurveUserInfoKey]!.integerValue
        
        let rect = n.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        toolBarBottomCons!.constant = rect.origin.y - UIScreen.mainScreen().bounds.size.height
        
        UIView.animateWithDuration(1.0) { () -> Void in
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
            self.view.layoutIfNeeded()
        }
        
    }
    
    private func removedKeyboardNotification() {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    // MARK: - 准备视图
    private func prepareTextView() {
        
        view.addSubview(textView)
        view.addSubview(photoSelectorVC.view)
        textView.ff_AlignInner(type: ff_AlignType.TopLeft, referView: view, size: nil)
        textView.ff_AlignVertical(type: ff_AlignType.TopRight, referView: toolbar, size: nil)
        
        textView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        textView.addSubview(placeHolderLabel)
        placeHolderLabel.ff_AlignInner(type: ff_AlignType.TopLeft, referView: textView, size: nil, offset: CGPoint(x: 5, y: 8))
        
        textView.delegate = self
    }
    
    private func prepareToolbar() {
        toolbar = UIToolbar()
        toolbar.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        view.addSubview(toolbar)
        
        let constranit = toolbar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: UIScreen.mainScreen().bounds.size.width, height: 44))
        // 取出底部约束
        toolBarBottomCons = toolbar.ff_Constraint(constranit, attribute: NSLayoutAttribute.Bottom)
        
        // 定义一个数组
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "pickPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "action": "inputEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        
        var items:[UIBarButtonItem] = [UIBarButtonItem]()
        for dict in itemSettings {
            
            let imgName = dict["imageName"]

            let button = UIBarButtonItem(imageName: imgName!, target: self, action: dict["action"])
            let itemSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
            
            items.append(button)
            items.append(itemSpace)
            
        }
        
        items.removeLast()
        toolbar.items = items
    }
    
    private func prepareNavgationBar() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus")
        navigationItem.rightBarButtonItem?.enabled = false
        
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 36))
        let topLabel = UILabel(fontSize: 15, fontColor: UIColor.darkGrayColor())
        topLabel.text = "发微博"
        topLabel.sizeToFit()
        
        let bottomLabel = UILabel(fontSize: 14, fontColor: UIColor.lightGrayColor())
        bottomLabel.text = UserAccount.sharedAccount?.name
        bottomLabel.sizeToFit()
        
        titleView.addSubview(topLabel)
        titleView.addSubview(bottomLabel)
        
        topLabel.ff_AlignInner(type: ff_AlignType.TopCenter, referView: titleView, size: nil)
        bottomLabel.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: titleView, size: nil)
        
        navigationItem.titleView = titleView
        
    }
    
    // MARK: - 懒加载控件
    private lazy var textView:UITextView = {
       let textView = UITextView()
        textView.alwaysBounceVertical = true
        textView.textColor = UIColor.darkGrayColor()
//        textView.text = "分享新鲜事..."
        textView.font = UIFont.systemFontOfSize(18)
        textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        return textView
    }()
  
    private lazy var toolbar = UIToolbar()
    
    // 占位标签
    private lazy var placeHolderLabel:UILabel = {
        
       let label = UILabel(fontSize: 18, fontColor: UIColor.darkGrayColor())
        label.text = "分享新鲜事..."
        label.textColor = UIColor.darkGrayColor()
        label.sizeToFit()
        
        return label
    }()
 
}

extension ComposeViewController:UITextViewDelegate {
    
    func textViewDidChange(textView: UITextView) {
//        placeHolderLabel.hidden = (textView.text.characters.count != 0)
        placeHolderLabel.hidden = textView.hasText()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}
